import { ethers } from "ethers";
import store from "../store";
import { userContract,usdtContract } from "./config";
import { userAbi } from "./abi/userAbi";
import eth from "./eth";
import { getDate } from "@/utils/index.js";
import AESUtils from "@/utils/AES.js";
import { IPFS_PUBLIC_URL } from "@/api/User.js";
import IndexDBCache from "@/hooks/sql/useOrder.js";
import { showToast } from "vant";
const orderDB = new IndexDBCache();
const pageSize = 100;
const sumStart = (end) => {
  return end + 1 - pageSize > 0 ? end + 1 - pageSize : 0;
};
const pageNum = (params) => {
  params.end = params.start - 1;
  params.start = sumStart(params.end);
  return params;
};
let provider, Contract, signer, ContractWithSinger;
try {
  provider = new ethers.providers.Web3Provider(window.ethereum);
  Contract = new ethers.Contract(
    userContract,
    userAbi.abi,
    provider
  );
  signer = provider.getSigner();
  ContractWithSinger = Contract.connect(signer);
} catch (error) {}
let times = 0
const userEth = {
  Contract,
  ContractWithSinger,
  async getCashPledge(account) {
    let price = 0
    try {
      // btc价格
      price = parseFloat(Number(ethers.utils.formatUnits(await Contract.tarderAmount(),usdtContract[3])).toFixed(2));
    } catch (err) {
    } finally {
      store.commit("changeCashPledge", price);
      return price;
    }
  },
  async getPlatformFee(account) {
    let price = 0
    try {
      // btc价格
       let data  = await Contract.getPlatformParam()
       let fee1 = Number(ethers.utils.formatUnits(data[3],4));
       let fee2 = Number(ethers.utils.formatUnits(data[4],4));
       let fee3 = Number(ethers.utils.formatUnits(data[5],4));
       price = fee1 + fee2 + fee3

    } catch (err) {
    } finally {
      store.commit("changePlatformFee", price);
      return price;
    }
  },
  async getTraderDetail(account) {
    let realAccount = ''
    try {
      await orderDB.initDB();
      let myAccount = await eth.getAccount();
      realAccount = account || myAccount
      let data = await Contract.traderList(realAccount);
      let obj = this.getShop(data)
      let res = await orderDB.getDataByKey("shopList", obj.account);
      let allobj = obj;
      if (res && res[0] && res[0].account) {
        allobj = Object.assign(res[0], obj);
      }
      if(store.state.address==realAccount){
        store.commit("changeMyShop",allobj)
      }
      // 如果是自己更新我的交易员
      await orderDB.updateData("shopList", allobj);
      return allobj
    } catch (error) {
      // setTimeout(()=>{
      //   showToast('进来次' + times + error)

      // },10000)
    }

  },  
  // 获取审核中的交易员
  async getApprovedTraders(status) {
    // 0 1 2 3
    // 0 审核中 1 上架 2 下架 3 拒绝
    await orderDB.initDB();
    let params = {
      page: 1,
      pageSize:pageSize
    };
    let first = true;
    let allArr = [];
    const onload = async () => {
      let arr = [];
      try {
        let data = await ContractWithSinger.getTradersByStatus(
          params.page,
          params.pageSize,
          status
        );
        let allPromise = [];
        data.forEach((e) => {
          if(e.name){
            allPromise.push(this.getShop(e));
          }
        });
        let allData = await Promise.all(allPromise);
        allData.forEach(async (obj, index) => {
          arr.unshift(obj);
          let res = await orderDB.getDataByKey("shopList", obj.account);
          let allobj = obj;
          if (res && res[0] && res[0].id) {
            allobj = Object.assign(res[0], obj);
          }
          await orderDB.updateData("shopList", allobj);
        });
        allArr = [...allArr, ...arr];
        if(status==0){
          store.commit("changeUnCheckedShop", [...allArr]);
        }else if(status==1){
          store.commit("changeShopList", [...allArr]);
        }else if(status==2){
         store.commit("changeOutShop", [...allArr]);
        }
        if (data.length == pageSize) {
          params.page++;
          await onload();
        } else {

        }
      } catch (err) {
        if(status==0){
          store.commit("changeUnCheckedShop", [...allArr]);
        }else if(status==1){
          store.commit("changeShopList", [...allArr]);
        }else if(status==2){
         store.commit("changeOutShop", [...allArr]);
        }
      } finally {
      }
    };
    await onload();
  },
  async getUserItem(account) {
    let obj = {};
    try {
      await orderDB.initDB();
      obj = await orderDB.getDataByKey("userList", account);
      if (obj && obj.length > 0) {
        return obj[0];
      }
    } catch (error) {}
    // 先取本地 没有取线上
    obj = await this.getUseInfo(account);
    return obj;
  },
  async getMinFee(account) {
    let price = 0
    try {
      // btc价格
      price = Number(ethers.utils.formatUnits(await Contract.minFee(),4));
    } catch (err) {
    } finally {
      store.commit("changeMinFee", price);
      return price;
    }
  },
  async getTimeList(way) {
    try {
      let arr = await Contract.getTimesByWay(way,0,100)
      let allPromise = [];
      arr.forEach((id) => {
        allPromise.push(this.getTime(id));
      });
      let allData = await Promise.all(allPromise);
      if(way==0){
        store.commit('changeFixedTime',allData)
      }else{
        store.commit('changeFreeTime',allData)
      }
      return allData;
    } catch (error) {
      return [];
    }
  },
  async getUserList(ids) {
    try {
      let arr = ids.split(",");
      let allPromise = [];
      arr.forEach((id) => {
        allPromise.push(this.getUserItem(id));
      });
      let allData = await Promise.all(allPromise);
      return allData;
    } catch (error) {
      return [];
    }
  },
  getShop(res) {
    try {
      return {
        name: res.name,
        describe:res.describe,
        phone: res.phone,
        url:IPFS_PUBLIC_URL + res.icon,
        tipRate: ethers.utils.formatUnits(res.tipRate,4),
        status: ethers.utils.formatUnits(res.status, 0),
        account: res.owner.toLowerCase(),
        other:res.other,
        amount: ethers.utils.formatUnits(res.amount, usdtContract[3]),
        createTime:getDate(res.createTime * 1000),
      };
    } catch (err) {
      return null;
    }
  },
  getTime(res) {
    try {
      return {
        id: Number(ethers.utils.formatUnits(res.id,0)) ,
        name: res.name,
        day: ethers.utils.formatUnits(res.day,0),
        way: ethers.utils.formatUnits(res.way,0),
        rate:ethers.utils.formatUnits(res.rate,4),
        isActive:res.isActive
      };
    } catch (err) {
      return null;
    }
  },
  getUser(res,id) {
    try {
      return {
        describe: res.describe,
        nickname: res.name,
        owner: res.owner.toLowerCase()==store.state.address0?id:res.owner.toLowerCase(),
        avatar: res.icon? IPFS_PUBLIC_URL + res.icon:'',
        trader: res.trader&&res.trader.toLowerCase(),
        isCloseOut:res.isCloseOut
      };
    } catch (err) {
      return null;
    }
  },
  async admins(account) {
    let myAccount = await eth.getAccount();
    let isAdmin = false;
    try {
      isAdmin = await Contract.admins(account || myAccount);
      store.commit("changeAdmin", isAdmin);
    } catch (err) {
      store.commit("changeAdmin", isAdmin);
    }
  },
  async getUseInfo(id) {
    let obj = {};
    try {
      let item = await Contract.userList(id);
      obj = this.getUser(item,id);
    } catch (err) {
    } finally {
      return obj;
    }
  },
};
export default userEth;
